package com.xj.openapi4j.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xj.dao.InventoryDao;
import com.xj.entity.InvUpdateInfo;
import com.xj.isv.service.OpenApiRequestService;
import com.xj.openapi4j.service.token.U8Token;
import com.xj.openapi4j.service.token.YsToken;
import com.xj.openapi4j.util.HttpUtil;
import com.xj.openapi4j.util.RequestTool;
import com.xj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
@EnableScheduling
public class StockService {
    @Value("${u8AppKey}")
    String u8AppKey;

    @Value("${u8AppSecret}")
    String u8AppSecret;

    @Value("${u8ApiUrl}")
    String u8ApiUrl;

    @Value("${fromAccount}")
    String from_account;

    @Autowired
    U8Token u8Token;

    @Autowired
    OpenApiRequestService openApiRequestService;
    @Value("${AppKey}")
    String  AppKey;

    @Value("${AppSecret}")
    String  suiteSecret;

    @Value("${tenantId}")
    String  tenantId;
    @Autowired
    YsToken ysToken;
    @Autowired
    InventoryDao inventoryDao;

    private static List<String> categoryList=new ArrayList<>();
      static {
          categoryList.add("02003001");
          categoryList.add("02003002");
          categoryList.add("02003003");
          categoryList.add("02003004");
          categoryList.add("02003005");
          categoryList.add("02003006");
          categoryList.add("02003007");
    }

    //存量同步，现存量变化时，将变化的invcode存入xj_inv表中
    public  void  transIncrement() throws Exception{
         Date date=new Date();
        List<InvUpdateInfo> list= inventoryDao.getInvUpdateInfoByCategory("stock");
        log.info("xj_inv  stocklist={}",list.size());
        Set<String> set=list.stream().map(obj->obj.getCinvcode()).collect(Collectors.toSet());
        if(set.size()==0){
            return;
        }else if(set.size()<50){
            JSONArray jsonArray=new JSONArray();
            for(String cinvcode:set){
                jsonArray.addAll(getU8tock(cinvcode));
            }
            if(!CollectionUtils.isEmpty(jsonArray)){
                transCurrentStock(jsonArray);
            }
        }else {
            transStockAll();
        }
        List<Integer> ids=list.stream().map(obj->obj.getId()).collect(Collectors.toList());
        inventoryDao.deleteAllByCategory("stock",date);
      }

    public  void  transInventory(String invcode) throws Exception{
        if(StringUtils.isNotEmpty(invcode)) {
            JSONArray jsonArray = getU8tock(invcode);
            if(!CollectionUtils.isEmpty(jsonArray)){
                transCurrentStock(jsonArray);
            }

        }else {
            transStockAll();
        }
    }


      //批量更新
    public  void   transStockAll() throws Exception{
        for(String  category: categoryList){
            List<Map<String,Object>> inventoryList=this.inventoryDao.getCurrentStock(category);
            log.info("category={},inventoryList.size={}",category,inventoryList.size());
            JSONArray result=new JSONArray();
            for(Map<String,Object> map:inventoryList){
                JSONObject data = new JSONObject();
                data.put("_status", "Insert");
                data.put("org", "001");
                data.put("warehouse", "bzp");
                data.put("product", map.get("invcode").toString());
                data.put("productsku", map.get("invcode").toString());
                data.put("currentqty", Double.valueOf(map.get("availqty")==null?"0":map.get("availqty").toString()));
                result.add(data);
            }
            log.info("category={},result.size={}",category,result.size());
            transCurrentStock(result);
        }
    }


    public JSONArray getU8tock(String  cinvcode) throws Exception {
        String url = "https://api.yonyouup.com/api/currentstock/batch_get";
        Map map = new HashMap();
        map.put("from_account", from_account);
        map.put("to_account", from_account);
        map.put("app_key", u8AppKey);
        map.put("app_secret", u8AppSecret);
        map.put("page_index","1");
        map.put("rows_per_page","10");
        map.put("invcode_begin",cinvcode);
        map.put("invcode_end",cinvcode);
        map.put("whcode_begin","bzp");
        map.put("whcode_end","bzp");
        String token = u8Token.getToken();
        map.put("token", token);
        String str = RequestTool.doGet(url, map);
        JSONObject jsonObject = JSONObject.parseObject(str);
        JSONArray jsonArray = jsonObject.getJSONArray("currentstock");
        JSONArray result=new JSONArray() ;
        if(CollectionUtils.isEmpty(jsonArray)){
            log.info("u8 stock data=null");
            JSONObject data = new JSONObject();
            data.put("_status", "Insert");
            data.put("org", "001");
            data.put("warehouse", "bzp");
            data.put("product", cinvcode);
            data.put("productsku", cinvcode);
            data.put("currentqty", 0);
            result.add(data);
            return  result;
         }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            JSONObject data = new JSONObject();
            data.put("_status", "Insert");
            data.put("org", "001");
            data.put("warehouse", "bzp");
            data.put("product", jsonObject1.getString("invcode"));
            data.put("productsku", jsonObject1.getString("invcode"));
            data.put("currentqty", jsonObject1.getDoubleValue("availqty"));
            result.add(data);
        }
        return result;
    }

    public  void  transCurrentStock(JSONArray  data)  throws  Exception{
        if(CollectionUtils.isEmpty(data)){
            return;
        }
        String token=ysToken.getToken();
        String requestUrl = "https://c3.yonyoucloud.com/iuap-api-auth/yonbip/scm/stockanalysis/forcesave?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        int page = data.size() / 50;
        for (int i = 0; i <= page; i++) {
            int end = (i + 1) * 50;
            if (end > data.size()) {
                end = data.size();
            }
            List subdata = data.subList(i * 50, end);
            jsonObject.put("data", subdata);
            String str = HttpUtil.post(requestUrl, jsonObject.toJSONString());
            log.info("trans stock resust={}",str);
        }
    }
}
